package com.jlu.utils;


import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author freedom
 * @DATE 2017/5/17 0017 23:07.
 * see   Mysql数据库操作类
 */
public class MySqlDB {
    private static Connection connection;
    private static PreparedStatement prst;
    private static ResultSet rs;
    private static String url="jdbc:mysql://localhost:3306/mobilecloud";
    private static String usename="root";
    private static String password="king159202";
    static{
        try {
            Class.forName("com.mysql.jdbc.Driver");
            connection= DriverManager.getConnection(url, usename, password);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     *author freedom
     *see 对数据库进行增删改操作
     *@参数 String 对应的sql语句
     *@返回类型 int 影响的行数
     *2016-5-28 下午02:42:57
     * @param sql
     * @return
     */
    public static int update(String sql){
        int result=0;
        try {
            prst=connection.prepareStatement(sql);
            result=prst.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return result;
    }

    /**
     *author freedom
     *see 把数据从数据库中取出并存到内存中
     *@参数 String 查询的sql语句
     *@返回类型 List
     *2016-5-28 下午02:54:59
     * @param sql
     * @return
     */
    public static List<Map<String, Object>> query(String sql){
        List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
        try {
            prst= connection.prepareStatement(sql);
            rs=prst.executeQuery();
            while(rs.next()){
                ResultSetMetaData rsmd = rs.getMetaData();
                int columnCount = rsmd.getColumnCount();
                Map<String, Object> map =new HashMap<String, Object>();
                for (int i = 1; i <=columnCount; i++) {
                    String columnName = rsmd.getColumnName(i);
                    Object columnValue=rs.getObject(columnName);
                    map.put(columnName, columnValue);
                }
                list.add(map);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     *author freedom
     *see 关闭数据库连接
     *@参数 void
     *@返回类型 void
     *2016-5-28 下午02:58:05
     */
    public static void close(){
        try {
            rs.close();
            prst.close();
            connection.close();

        } catch (SQLException e) {
            e.printStackTrace();
        }

    }
}
